package com.sunxd.study.easyrules.api;

import com.sunxd.study.easyrules.core.RuleProxy;

import java.util.*;

/**
 * @author sun.xd
 * @description: description
 * @date 2022/3/29 16:36
 */
public class Rules implements Iterable<Rule> {

    private Set<Rule> rules = new TreeSet<>();

    public Rules(Set<Rule> rules){
        this.rules = new TreeSet<>(rules);
    }

    public Rules(Rule... rules){
        Collections.addAll(this.rules,rules);
    }

    public Rules(Object... objects){

    }

    public void register(Object... rules){
        Objects.requireNonNull(rules);
        for (Object rule: rules) {
            Objects.requireNonNull(rules);
            this.rules.add(RuleProxy.asRule(rule));
        }
    }

    /**
     * Unregister one or more rules.
     *
     * @param rules to unregister, must not be null
     */
    public void unregister(Object... rules) {
        Objects.requireNonNull(rules);
        for (Object rule : rules) {
            Objects.requireNonNull(rule);
            this.rules.remove(RuleProxy.asRule(rule));
        }
    }

    /**
     * Unregister a rule by name.
     *
     * @param ruleName name of the rule to unregister, must not be null
     */
    public void unregister(final String ruleName) {
        Objects.requireNonNull(ruleName);
        Rule rule = findRuleByName(ruleName);
        if (rule != null) {
            unregister(rule);
        }
    }

    public boolean isEmpty() {
        return rules.isEmpty();
    }

    private Rule findRuleByName(String ruleName) {
        return rules.stream()
                .filter(rule -> rule.getName().equalsIgnoreCase(ruleName))
                .findFirst()
                .orElse(null);
    }


    @Override
    public Iterator<Rule> iterator() {
        return rules.iterator();
    }
}
